/* ********************************************************************************
 *      Copyright:  (C) 2025 ZYT
 *                  All rights reserved.
 *  
 *       Filename:  socket.c
 *    Description:  This file 
 *                    
 *        Version:  1.0.0(07/04/25)
 *         Author:  Zhang yuting <zhangyuting@163.com>
 *      ChangeLog:  1, Release initial version on "07/04/25 22:23:27"
 *                       
 *********************************************************************************/

#include "socket.h"

 //       Description:  create and bind sockfd, and start to listen sockfd.
 //      return value:  On error, -1 is returned. On success, sockfd is returned.
int socket_server_init(int serv_port)
{
        int                  rv = 0;
        int                  sockfd;
        struct sockaddr_in   servaddr;
        int                  on = 1;

        if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
        {
                dbg_printf("create sockfd failure: %s\n", strerror(errno));
                return -1;
        }
        dbg_printf("create sockfd[%d] successfully\n", sockfd);

        setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

        memset(&servaddr, 0, sizeof(servaddr));
        servaddr.sin_family = AF_INET;
        servaddr.sin_port = htons(serv_port);
        servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
        if(bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0 )
        {
                dbg_printf("bind sockfd failure: %s\n", strerror(errno));
                rv = -3;
                close(sockfd);
        }
        dbg_printf("bind sockfd[%d] listen on port[%d] successfully\n", sockfd, serv_port);

        if( listen(sockfd, 64) < 0 )
        {
                dbg_printf("listen sockfd failure: %s\n", strerror(errno));
                rv = -4;
                close(sockfd);
        }

        return sockfd;
}

